#!/usr/bin/python3
# -*- coding: utf-8 -*-

from sanic import Sanic
from sanic import response
from sanicdb import SanicDB
from sanic.log import logger
import asyncio
import random


web_app = Sanic("app-test-utils")

db = SanicDB('ooooo-test-db.cwjlbbkjnbiz.eu-west-2.rds.amazonaws.com', 'db_ooooo', 'db_ooooo_rw', 'DB_ooooo_rw', sanic=web_app)

'''
跨域返回信息头
'''
headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "*",
    "Access-Control-Allow-Methods": "*",
    "Access-Control-Expose-Headers": "*",
    "Access-Control-Allow-Credentials": "*"
}


@web_app.middleware('request')
async def cros(request):
    '''
    sanic 中间件 请求拦截
    '''
    if request.method == 'OPTIONS':
        return response.empty(headers=headers, status=204)


@web_app.middleware('response')
async def custom_banner(request, response):
    '''
    sanic 中间件 响应拦截
    '''
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = '*'
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Expose-Headers'] = '*'
    response.headers['Access-Control-Allow-Credentials'] = '*'


@web_app.route("/test", methods=['OPTIONS', 'POST', 'GET'])
async def test(request):
    '''
    测试环境App info
    :param request:
    :return: appInfo
    '''
    logger.info(f'{request}')
    return response.json({"code": 0}, headers=headers)


@web_app.route('/test1', methods=['GET', 'POST', 'OPTIONS'])
async def index(request):
    sql = 'select * from db_ooooo.t_video_info'
    print(f'执行sql:{sql}')
    data = await web_app.db.query(sql)
    print(f'响应数据:{data}')
    return response.json(response.dumps(data))

if __name__ == '__main__':
    web_app.run(host="0.0.0.0", port=5001, debug=True)